<!--  -->
<template>
  <el-tabs class="home-box flex-row" v-model="activeName">
    <el-tab-pane class="flex-col" label="设备监控" name="first">
      <div class="tab-title">
        <label class="title-font">工厂/工序/设备: </label
        ><el-cascader
          v-model="optionInput"
          ref="cascader"
          style="width: 10vw"
          placeholder="请选择需要监控的设备"
          :options="homeOptions"
          :props="{
            value: 'StructGuid',
            label: 'DisplayName',
            children: 'Children',
          }"
          filterable
        ></el-cascader>
        <el-button @click="SelectMonitorVar" type="primary">搜索</el-button>
        <!-- <el-button @click="ChangeConnectType" type="primary">修改</el-button> -->
      </div>
      <div class="flex-row">
        <div class="flex-col" style="flex: 2">
          <div class="table-title"><span class="title">连接监控</span></div>
          <el-table
            header-fixed
            ref="connectTable"
            :height="300"
            v-loading="connectLoading"
            class="table-border"
            :data="connectData"
            style="width: 100%; margin-bottom: 1vh; overflow: auto"
          >
            <el-table-column prop="Line" label="工厂" width="180">
            </el-table-column>
            <el-table-column prop="Process" label="工序" width="180">
            </el-table-column>
            <el-table-column prop="Equip" label="设备"> </el-table-column>
            <el-table-column prop="Part" label="部件"> </el-table-column>
            <el-table-column
              prop="State"
              :filters="partsFilterName"
              :filter-method="partsFilterHandler"
              label="连接状态"
            >
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.State == 1 ? 'success' : 'danger'"
                  size="medium"
                  >{{ scope.row.State == 1 ? "正常" : "异常" }}</el-tag
                >
              </template>
            </el-table-column>
            <!-- <el-table-column
              prop="State"
              icon="el-icon-more-outline"
              label="连接状态"
            >
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.State === '正常' ? 'success' : 'danger'"
                  size="medium"
                  >{{ scope.row.State }}</el-tag
                >
              </template>
              <template slot="header" slot-scope="scope">
                <span class="el-table__column-filter-trigger">
                  <i class="el-icon-more-outline"></i>
                </span>

                <FilterHelp
                  :column="scope.column"
                  field-name="type"
                  filter-type="date"
                  :custom-arr-list="dictList"
                  @tableFilter="tableFilter"
                  @resetFilter="tableFilterReset"
                ></FilterHelp>
              </template>
            </el-table-column> -->
            <el-table-column prop="UpdateTime" label="最近一次成功连接时间">
            </el-table-column>
          </el-table>
          <div class="table-title"><span class="title">变量监控</span></div>
          <el-table
            header-fixed
            ref="monitorTable"
            v-loading="monitorLoading"
            class="table-border"
            :height="300"
            :data="varTableData"
            style="width: 100%; overflow: auto"
          >
            <el-table-column prop="Line" label="工厂" width="180">
            </el-table-column>
            <el-table-column prop="Process" label="工序" width="180">
            </el-table-column>
            <el-table-column prop="Equip" label="设备"> </el-table-column>
            <el-table-column prop="Name">
              <template #header>
                <span style="margin-right: 10px">监控变量</span>
                <el-popover
                  placement="bottom"
                  width="300"
                  trigger="click"
                  popper-class="filter-table-input"
                  ref="popoverMonitor"
                  @hide="
                    () => {
                      (monitorDataTree = [
                        {
                          id: 1,
                          label: '全选',
                          children: [],
                        },
                      ]),
                        (monitorDataTree[0].children = varTableDataAlways.map(
                          (item) => ({
                            id: item.Name,
                            label: item.Name,
                          })
                        ));
                      filterText = '';
                      $refs.tree.setCheckedKeys(defaultCheckedKeys);
                      monitorFilterNameChecked = monitorDataTree[0].children
                        .filter((item) => defaultCheckedKeys.includes(item.id))
                        .map((item) => ({
                          label: item.label,
                          id: item.id,
                        }));
                    }
                  "
                  @show="
                    () => {
                      defaultCheckedKeys = monitorFilterNameChecked.map(
                        (item) => item.id
                      );
                    }
                  "
                >
                  <i
                    slot="reference"
                    class="el-icon-s-unfold table-filter-icon"
                  />
                  <!-- content -->
                  <section class="table-filter-btns">
                    <el-input
                      placeholder="输入关键字进行过滤"
                      prefix-icon="el-icon-search"
                      v-model="filterText"
                    ></el-input>
                    <el-tree
                      class="filter-tree"
                      :default-expand-all="true"
                      :data="monitorDataTree"
                      :props="defaultProps"
                      :filter-node-method="filterNode"
                      :expand-on-click-node="false"
                      show-checkbox
                      ref="tree"
                      node-key="id"
                      @check-change="handleCheckChange"
                      :default-checked-keys="defaultCheckedKeys"
                    ></el-tree>
                    <div class="tree-footer">
                      <el-button
                        type="default"
                        @click="
                          () => {
                            $refs.popoverMonitor.doClose(); // 关闭el-popover
                          }
                        "
                        >取消</el-button
                      >
                      <el-button
                        type="primary"
                        icon="el-icon-search"
                        @click="combinedFilterHandler"
                        >筛选</el-button
                      >
                    </div>
                  </section>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="Description">
              <template #header>
                <span style="margin-right: 10px">变量描述</span>
                <el-popover
                  placement="bottom"
                  width="300"
                  trigger="click"
                  popper-class="filter-table-input"
                  ref="popover"
                  @hide="
                    () => {
                      monitorDataDescTree = [
                        {
                          id: 1,
                          label: '全选',
                          children: [],
                        },
                      ];

                      const uniqueChildren = [];
                      const uniqueLabels = new Set();

                      varTableDataAlways.forEach((item) => {
                        if (!uniqueLabels.has(item.Description)) {
                          uniqueLabels.add(item.Description);
                          uniqueChildren.push({
                            id: item.Description,
                            label: item.Description,
                          });
                        }
                      });

                      monitorDataDescTree[0].children = uniqueChildren;
                      filterText2 = '';
                      $refs.tree1.setCheckedKeys(defaultCheckedKeys2);
                      monitorFilterDescChecked = monitorDataDescTree[0].children
                        .filter((item) => defaultCheckedKeys2.includes(item.id))
                        .map((item) => ({
                          label: item.label,
                          id: item.id,
                        }));
                    }
                  "
                  @show="
                    () => {
                      defaultCheckedKeys2 = monitorFilterDescChecked.map(
                        (item) => item.id
                      );
                    }
                  "
                >
                  <i
                    slot="reference"
                    class="el-icon-s-unfold table-filter-icon"
                  />
                  <!-- content -->
                  <section class="table-filter-btns">
                    <el-input
                      placeholder="输入关键字进行过滤"
                      prefix-icon="el-icon-search"
                      v-model="filterText2"
                    ></el-input>
                    <el-tree
                      class="filter-tree"
                      :default-expand-all="true"
                      :data="monitorDataDescTree"
                      :props="defaultProps"
                      :filter-node-method="filterNode"
                      :expand-on-click-node="false"
                      show-checkbox
                      ref="tree1"
                      node-key="id"
                      @check-change="handleCheckDescChange"
                      :default-checked-keys="defaultCheckedKeys2"
                    ></el-tree>
                    <div class="tree-footer">
                      <el-button
                        type="default"
                        @click="
                          () => {
                            $refs.popover.doClose(); // 关闭el-popover
                          }
                        "
                        >取消</el-button
                      >
                      <el-button
                        type="primary"
                        icon="el-icon-search"
                        @click="combinedFilterHandler"
                        >筛选</el-button
                      >
                    </div>
                  </section>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="OldValue" label="当前值">
              <template slot-scope="scope">
                <span v-if="scope.row.OldValue == '?'" style="color: red">{{
                  scope.row.OldValue
                }}</span>
                <span v-else>{{ scope.row.OldValue }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="Value" label="清洗后值">
              <template slot-scope="scope">
                <span v-if="scope.row.Value == '?'" style="color: red">{{
                  scope.row.Value
                }}</span>
                <span v-else>{{ scope.row.Value }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="Time" label="耗时(ms)"> </el-table-column>
            <el-table-column prop="UpdateTime" label="最近一次读取时间">
            </el-table-column>
          </el-table>
        </div>
        <div class="flex-col border">
          <span class="title">运行日志</span>
          <div style="border-bottom: 0.05vw solid #e7e7e7"></div>
          <el-tabs v-model="logModel" style="padding: 0 1vw; height: 100%">
            <el-tab-pane label="错误" name="error">
              <logTable :logsArray="Errorlogs"></logTable>
            </el-tab-pane>
            <el-tab-pane label="警告" name="warn">
              <logTable :logsArray="Warnlogs"></logTable>
            </el-tab-pane>
            <el-tab-pane
              style="width: 100%; height: 100%; overflow: hidden"
              label="信息"
              name="debug"
            >
              <LogTable :logsArray="Infologs"></LogTable>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-tab-pane>
    <!-- <el-tab-pane label="资源监控" name="second">配置管理</el-tab-pane> -->
  </el-tabs>
</template>

<script>
import JSONBig from "json-bigint";
import $store from "../../store";
import $http from "../../utils/apiHelper";
import LogTable from "@/views/pages/components/LogTable";
import axios from "axios";
import systemconfig from "@/store/modules/systemconfig";
const Stomp = require("stompjs");
export const MQTT_SERVICE = "ws://10.33.35.7:15674/ws"; // mqtt服务地址
export const MQTT_USERNAME = "root"; // 连接用户名
export const MQTT_PASSWORD = "root"; //  连接密码
export const Virtual_host = "bx"; //  侦听器端口
export default {
  components: { LogTable },
  computed: {
    partsFilterName() {
      if (this.connectData) {
        let p = this.connectData.map((m) => {
          if (m.State) {
            return {
              text: m.State == 1 ? "正常" : "异常",
              value: m.State == 1 ? "正常" : "异常",
            };
          } else {
            return { text: "", value: "" };
          }
        });
        return p.reduce((accumulator, currentItem) => {
          if (
            !accumulator.some(
              (item) =>
                item.text === currentItem.text &&
                item.value === currentItem.value
            )
          ) {
            accumulator.push(currentItem);
          }
          return accumulator;
        }, []);
      } else {
        return null;
      }
    },
    // monitorFilterName() {
    //   if (this.varTableData) {
    //     let p = this.varTableData.map((m) => {
    //       if (m.Name) {
    //         return { text: m.Name, value: m.Name };
    //       } else {
    //         return { text: "", value: "" };
    //       }
    //     });
    //     return p.reduce((accumulator, currentItem) => {
    //       if (
    //         !accumulator.some(
    //           (item) =>
    //             item.text === currentItem.text &&
    //             item.value === currentItem.value
    //         )
    //       ) {
    //         accumulator.push(currentItem);
    //       }
    //       return accumulator;
    //     }, []);
    //   } else {
    //     return null;
    //   }
    // },
    // descriptFilterName() {
    //   if (this.varTableData) {
    //     let p = this.varTableData.map((m) => {
    //       if (m.Description) {
    //         return { text: m.Description, value: m.Description };
    //       } else {
    //         return { text: "", value: "" };
    //       }
    //     });
    //     return p.reduce((accumulator, currentItem) => {
    //       if (
    //         !accumulator.some(
    //           (item) =>
    //             item.text === currentItem.text &&
    //             item.value === currentItem.value
    //         )
    //       ) {
    //         accumulator.push(currentItem);
    //       }
    //       return accumulator;
    //     }, []);
    //   } else {
    //     return null;
    //   }
    // },
  },
  data() {
    return {
      defaultCheckedKeys: [], // 保存原始的勾选状态,
      defaultCheckedKeys2: [], // 保存原始的勾选状态,
      filterText: "",
      filterText2: "",
      monitorFilterNameChecked: [],
      monitorFilterDescChecked: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      monitorDataTree: [
        {
          id: 1,
          label: "全选",
          children: [],
        },
      ],
      monitorDataDescTree: [
        {
          id: 1,
          label: "全选",
          children: [],
        },
      ],
      monitorLoading1: true,
      monitorLoading: false,
      connectLoading: false,
      optionInput: "",
      homeOptions: [],
      logModel: "error",
      Infologs: [],
      Warnlogs: [],
      Errorlogs: [],
      connectData: [],
      varTableData: [],
      varTableDataAlways: [],
      activeName: "first",
      client: "",
    };
  },
  async created() {
    this.mqtthuoquMsg();
  },
  methods: {
    // 其他方法...
    handleCheckChange(data, checked, indeterminate) {
      if (data.children) {
        return;
      }
      if (checked) {
        if (
          !this.monitorFilterNameChecked.some((item) => item.id === data.id)
        ) {
          this.monitorFilterNameChecked.push(data);
        }
      } else {
        const index = this.monitorFilterNameChecked.findIndex(
          (item) => item.id === data.id
        );
        if (index > -1) {
          this.monitorFilterNameChecked.splice(index, 1);
        }
      }
    },
    handleCheckDescChange(data, checked, indeterminate) {
      if (data.children) {
        return;
      }
      if (checked) {
        if (
          !this.monitorFilterDescChecked.some((item) => item.id === data.id)
        ) {
          this.monitorFilterDescChecked.push(data);
        }
      } else {
        const index = this.monitorFilterDescChecked.findIndex(
          (item) => item.id === data.id
        );
        if (index > -1) {
          this.monitorFilterDescChecked.splice(index, 1);
        }
      }
    },
    ChangeConnectType() {
      this.connectData[3].State = 2;
      //测试功能使用
      this.connectData.sort((a, b) => {
        if (a.State == 1 && b.State != 1) {
          return 1; // a 在 b 前面
        } else if (a.State != 1 && b.State == 1) {
          return -1; // a 在 b 后面
        } else {
          return 0; // 不改变顺序
        }
      });
    },
    findObjectBySortIndex(obj, sortIndex, msg, lable) {
      msg.push(obj.StructGuid);
      lable.push(obj.DisplayName);
      if (obj.SortIndex === sortIndex) {
        return { msg, lable };
      }
      let s = obj.Children;
      if (obj.Children && obj.Children.length > 0) {
        for (let i = 0; i < obj.Children.length; i++) {
          const child = obj.Children[i];
          const foundObject = this.findObjectBySortIndex(
            child,
            sortIndex,
            msg,
            lable
          );
          if (foundObject) {
            return { msg, lable };
          }
        }
      }
      return null;
    },

    combinedFilterHandler() {
      this.defaultCheckedKeys = this.monitorFilterNameChecked.map(
        (item) => item.id
      );
      this.defaultCheckedKeys2 = this.monitorFilterDescChecked.map(
        (item) => item.id
      );
      this.varTableData = this.varTableDataAlways.filter((itemAlways) => {
        return (
          (this.monitorFilterDescChecked.length === 0 ||
            this.monitorFilterDescChecked.some((itemChecked) => {
              this.$refs.popoverMonitor.doClose(); // 关闭el-popover
              this.$refs.popover.doClose(); // 关闭el-popover
              return itemAlways.Description === itemChecked.label;
            })) &&
          (this.monitorFilterNameChecked.length === 0 ||
            this.monitorFilterNameChecked.some((itemChecked) => {
              this.$refs.popoverMonitor.doClose(); // 关闭el-popover
              this.$refs.popover.doClose(); // 关闭el-popover
              return itemAlways.Name === itemChecked.label;
            }))
        );
      });
    },
    partsFilterHandler(value, row) {
      if (value == "正常") {
        return row.State == 1;
      } else {
        return row.State != 1;
      }
    },
    // 消息队列获取
    async mqtthuoquMsg() {
      const res = this.$store.state.systemconfig.system.find(
        (x) => x.ConfigName == "RabbitMq"
      );

      const settings = JSON.parse(res.Config);

      //初始化连接
      const headers = {
        login: settings.user,
        passcode: settings.passward,
      };
      this.client = Stomp.client(settings.ip);
      //进行连接
      this.client.connect(
        headers.login,
        headers.passcode,
        this.onConnected,
        this.onFailed,
        "/"
      );
      //this.client.onWebSocketClose
    },
    onConnected: function () {
      //订阅频道
      // const topic = "/exchange/Logs_exchange/SystemLog";
      const topic = "/exchange/Logs_exchange/DeviceLog";
      const dataTopic = "/exchange/Eap-Exchange/DataMonitor";
      const connectTopic = "/exchange/Eap-Exchange/ConnectionMonitor";
      //this.client.subscribe(topic, this.responseCallback, { id: 10010 });
      this.client.subscribe(dataTopic, this.responseCallback, { id: 10011 });
      this.client.subscribe(topic, this.responseLogData, { id: 10010 });
      this.client.subscribe(connectTopic, this.responseConnectData, {
        id: 10012,
      });
    },
    onFailed: function (frame) {
      console.log("MQ Failed: " + frame);
      this.$message.error("连接失败");
    },
    // 回传消息
    responseCallback: function (frame) {
      console.log("MQ msg=>" + frame.body);
      //接收消息处理
      //序列化消息
      let msg = JSONBig.parse(frame.body);
      if (msg.DataSnowID && msg.IsMemberOfArray) {
        //存在说明是变量监控,且为数组
        let varData = this.varTableDataAlways.find(
          (t) =>
            t.ID == String(msg.DataSnowID) &&
            t.IsArray == msg.IsMemberOfArray &&
            t.Index == msg.ArrayIndex
        );
        if (varData) {
          varData.Value = msg.NewValue;
          varData.OldValue = msg.OldValue;
          varData.UpdateTime = this.$moment(msg.ChangeTime)
            .utcOffset("+08:00")
            .format("yyyy/MM/DD HH:mm:ss");
          varData.Time = msg.TimeConsunming;
        }
      } else if (msg.DataSnowID && !msg.IsMemberOfArray) {
        //非数组变量
        let varData = this.varTableDataAlways.find(
          (t) => t.ID == String(msg.DataSnowID)
        );
        if (varData) {
          varData.Value = msg.NewValue;
          varData.OldValue = msg.OldValue;
          varData.UpdateTime = this.$moment(msg.ChangeTime)
            .utcOffset("+08:00")
            .format("yyyy/MM/DD HH:mm:ss");
          varData.Time = msg.TimeConsunming;
        }
      }
    },
    responseConnectData(result) {
      console.log("responseConnectData msg=>" + result.body);
      let msg = JSON.parse(result.body);
      if (msg.ComponentID) {
        let connectMsg = this.connectData.find((t) => t.ID == msg.ComponentID);
        if (connectMsg) {
          connectMsg.State = msg.ConnectionState == 1;
          connectMsg.UpdateTime = this.$moment(msg.LastConnectTime)
            .utcOffset("+08:00")
            .format("yyyy/MM/DD HH:mm:ss");
          this.connectData.sort((a, b) => {
            if (a.State == 1 && b.State != 1) {
              return 1; // a 在 b 前面
            } else if (a.State != 1 && b.State == 1) {
              return -1; // a 在 b 后面
            } else {
              return 0; // 不改变顺序
            }
          });
        }
      }
    },
    responseLogData(result) {
      //let connectMsg = this.connectData.find((t) => t.ID == msg.ComponentID);
      console.log("responseConnectData msg=>" + result.body);
      let msg = JSONBig.parse(result.body);
      //let msg = JSON.parse(result.body);
      if (msg.Level) {
        // console.log(
        //   "msg.Properties.UserContext",
        //   String(msg.Properties.UserContext)
        // );
        // console.log("msg.Properties", msg.Properties);
        // console.log(
        //   "msg.Properties==",
        //   msg.Properties.UserContext,
        //   String(this.optionInput[2]),
        //   this.optionInput[2] == msg.Properties.UserContext
        // );
        if (
          this.optionInput[2] &&
          msg.Properties &&
          msg.Properties.UserContext &&
          String(msg.Properties.UserContext) === String(this.optionInput[2])
        ) {
          if (msg.Level == "Debug" || msg.Level == "Information") {
            //if(msg.)
            this.Infologs.unshift(
              this.$moment(msg.Timestamp)
                .utcOffset("+08:00")
                .format("yyyy/MM/DD HH:mm:ss") + msg.MessageTemplate
            );
            if (this.Infologs.length >= 300) {
              //限流去掉最后100个
              this.Infologs = this.Infologs.splice(
                this.Infologs.length - 101,
                100
              );
            }
          } else if (msg.Level == "Warning") {
            this.Warnlogs.unshift(
              this.$moment(msg.Timestamp)
                .utcOffset("+08:00")
                .format("yyyy/MM/DD HH:mm:ss") + msg.MessageTemplate
            );
            if (this.Warnlogs.length >= 300) {
              //限流去掉最后100个
              this.Warnlogs = this.Warnlogs.splice(
                this.Warnlogs.length - 101,
                100
              );
            }
          } else if (msg.Level == "Fatal" || msg.Level == "Error") {
            this.Errorlogs.unshift(
              this.$moment(msg.Timestamp)
                .utcOffset("+08:00")
                .format("yyyy/MM/DD HH:mm:ss") + msg.MessageTemplate
            );
            if (this.Errorlogs.length >= 300) {
              //限流去掉最后100个
              this.Errorlogs = this.Errorlogs.splice(
                this.Errorlogs.length - 101,
                100
              );
            }
          }
        }
      }
    },
    // 断开相应的连接
    close: function () {
      this.client.disconnect(function () {
        console.log("已退出账号");
      });
    },
    filterHomeOption: function filterTree(tree, level) {
      return tree.filter(function (node) {
        if (node.SortIndex >= level) {
          //不需要设备之下的node
          //delete node.Children;
          return false;
        } else if (node.Children) {
          node.Children = filterTree(node.Children, level);
        }
        if (node.SortIndex >= level - 1) {
          delete node.Children;
        }
        return true;
      });
    },
    async Refresh() {
      await $http.get("/EqManage/GetLineProcessDevPLCInfo").then((res) => {
        if (res.Data) {
          let option = this.filterHomeOption(res.Data, 4);

          this.homeOptions = option[0].Children;
          console.log("@@@Refresh done! this.homeOptions:", this.homeOptions);
        }
      });
    },
    SelectMonitorVar(value) {
      this.defaultCheckedKeys = [];
      this.defaultCheckedKeys2 = [];
      this.monitorFilterNameChecked = [];
      this.monitorFilterDescChecked = [];
      this.$refs.tree.setCheckedKeys([]);
      this.$refs.tree1.setCheckedKeys([]);
      this.Infologs = [];
      this.Warnlogs = [];
      this.Errorlogs = [];
      let param = "";
      if (value.msg) {
        param = value.msg.split("/");
      } else {
        param = this.$refs["cascader"].inputValue.split("/");
      }

      this.connectData = [];
      this.varTableData = [];
      this.varTableDataAlways = [];
      this.connectLoading = true;
      this.monitorLoading = true;
      $http
        .get(`/Monitor/GetMonitorVar?eqid=${this.optionInput[2]}`, {
          timeout: 20000, // 设置最大连接时长为5秒
        })
        .then((res) => {
          if (res.Data) {
            //处理PLC连接信息
            if (res.Data.PlcInfoModels) {
              res.Data.PlcInfoModels.forEach((m) => {
                this.connectData.push({
                  ID: m.ID,
                  Line: param[0],
                  Process: param[1],
                  Equip: param[2],
                  Part: m.alias,
                  State: m.state,
                  UpdateTime: m.connectTime,
                });
              });
            }
            if (res.Data.PlcDataInfoModels) {
              //重组PLC变量
              res.Data.PlcDataInfoModels.forEach((m) => {
                //非数组直接添加
                this.varTableData.push({
                  ID: m.id,
                  Index: m.index,
                  IsArray: m.isArray,
                  Line: param[0],
                  Process: param[1],
                  Equip: param[2],
                  Name: m.isArray ? m.alias + "[" + m.index + "]" : m.alias,
                  Description: m.desc,
                  Value: m.cleanedVal,
                  OldValue: m.currentVal,
                  Time: m.elapsedTime,
                  UpdateTime: m.updateTime,
                });
              });
            }
            if (res.Data.EQBizDatasModels) {
              //重组全局变量
              res.Data.EQBizDatasModels.forEach((m) => {
                this.varTableData.push({
                  ID: m.id,
                  Index: 0,
                  IsArray: m.isArray,
                  Line: m.monitorDataType == 2 ? "-" : param[0],
                  Process: m.monitorDataType == 2 ? "-" : param[1],
                  Equip: m.monitorDataType == 2 ? "-" : param[2],
                  Name: m.isArray ? m.alias + "[" + m.index + "]" : m.alias,
                  Description: m.desc,
                  Value: "-",
                  OldValue: m.currentVal,
                  Time: m.elapsedTime,
                  UpdateTime: m.updateTime,
                });
              });
            }

            this.varTableDataAlways = this.varTableData;
            let incrementId = 1;

            this.monitorDataTree[0].children = this.varTableDataAlways.map(
              (item) => ({
                id: item.Name,
                label: item.Name,
              })
            );

            const descriptionSet = new Set();
            const uniqueChildren = [];

            for (let i = 0; i < this.varTableDataAlways.length; i++) {
              const item = this.varTableDataAlways[i];
              if (!descriptionSet.has(item.Description)) {
                descriptionSet.add(item.Description);
                uniqueChildren.push({
                  id: item.Description,
                  label: item.Description,
                });
              }
            }

            this.monitorDataDescTree[0].children = uniqueChildren;
            //初始化筛选条件
            this.$refs.connectTable.clearFilter();
            this.$refs.monitorTable.clearFilter();
            this.connectLoading = false;
            this.monitorLoading = false;
          }
        })
        .catch(() => {
          this.connectLoading = false;
          this.monitorLoading = false;
        });
    },
    xclickfilter(scope) {
      console.log("这是scope", scope);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
  },

  watch: {
    filterText(val) {
      if (val != "") {
        this.monitorDataTree = this.varTableDataAlways
          .filter((item) => item.Name.includes(val))
          .map((item) => ({
            id: item.Name,
            label: item.Name,
          }));
      } else {
        (this.monitorDataTree = [
          {
            id: 1,
            label: "全选",
            children: [],
          },
        ]),
          (this.monitorDataTree[0].children = this.varTableDataAlways.map(
            (item) => ({
              id: item.Name,
              label: item.Name,
            })
          ));
      }
    },
    filterText2(val) {
      if (val !== "") {
        const uniqueLabels = new Set();
        this.monitorDataDescTree = this.varTableDataAlways
          .filter((item) => {
            if (
              !uniqueLabels.has(item.Description) &&
              item.Description.includes(val)
            ) {
              uniqueLabels.add(item.Description);
              return true;
            }
            return false;
          })
          .map((item) => ({
            id: item.Description,
            label: item.Description,
          }));
      } else {
        this.monitorDataDescTree = [
          {
            id: 1,
            label: "全选",
            children: [],
          },
        ];

        const uniqueChildren = [];
        const uniqueLabels = new Set();

        this.varTableDataAlways.forEach((item) => {
          if (!uniqueLabels.has(item.Description)) {
            uniqueLabels.add(item.Description);
            uniqueChildren.push({
              id: item.Description,
              label: item.Description,
            });
          }
        });

        this.monitorDataDescTree[0].children = uniqueChildren;
      }
    },
  },

  async mounted() {
    await this.Refresh();
    let res = this.findObjectBySortIndex(this.homeOptions[0], 3, [], []); //找到第一个第4级内容
    console.log(res);
    if (res) {
      this.optionInput = res.msg;
    }
    this.SelectMonitorVar({ msg: res.lable.join("/") });
  },
  beforeDestroy() {
    this.close();
  },
};
</script>
<style  scoped>
/* @import url(); 引入css类 */

.navigatorScroller {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}
::v-deep .el-tabs__content {
  height: 100%;
}

/* 隐藏伪元素 */
::v-deep.el-table::before {
  display: none !important;
}

.filter-tree {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  max-height: 100px; /* 设置树的最大高度，超过该高度将显示下拉框 */
  overflow-y: auto;
  padding: 10px; /* 增加树和边框之间的间距 */
}

.tree-footer {
  margin-top: 10px;
  text-align: center;
}
</style>